if(!this.JSON)this.JSON={};
(function(){function k(a){return a<10?"0"+a:a}function n(a){o.lastIndex=0;return o.test(a)?'"'+a.replace(o,function(c){var d=q[c];return typeof d==="string"?d:"\\u"+("0000"+c.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+a+'"'}function l(a,c){var d,f,i=g,e,b=c[a];if(b&&typeof b==="object"&&typeof b.toJSON==="function")b=b.toJSON(a);if(typeof j==="function")b=j.call(c,a,b);switch(typeof b){case "string":return n(b);case "number":return isFinite(b)?String(b):"null";case "boolean":case "null":return String(b);
case "object":if(!b)return"null";g+=m;e=[];if(Object.prototype.toString.apply(b)==="[object Array]"){f=b.length;for(a=0;a<f;a+=1)e[a]=l(a,b)||"null";c=e.length===0?"[]":g?"[\n"+g+e.join(",\n"+g)+"\n"+i+"]":"["+e.join(",")+"]";g=i;return c}if(j&&typeof j==="object"){f=j.length;for(a=0;a<f;a+=1){d=j[a];if(typeof d==="string")if(c=l(d,b))e.push(n(d)+(g?": ":":")+c)}}else for(d in b)if(Object.hasOwnProperty.call(b,d))if(c=l(d,b))e.push(n(d)+(g?": ":":")+c);c=e.length===0?"{}":g?"{\n"+g+e.join(",\n"+g)+
"\n"+i+"}":"{"+e.join(",")+"}";g=i;return c}}if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+k(this.getUTCMonth()+1)+"-"+k(this.getUTCDate())+"T"+k(this.getUTCHours())+":"+k(this.getUTCMinutes())+":"+k(this.getUTCSeconds())+"Z":null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()}}var p=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
o=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,g,m,q={"\u0008":"\\b","\t":"\\t","\n":"\\n","\u000c":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},j;if(typeof JSON.stringify!=="function")JSON.stringify=function(a,c,d){var f;m=g="";if(typeof d==="number")for(f=0;f<d;f+=1)m+=" ";else if(typeof d==="string")m=d;if((j=c)&&typeof c!=="function"&&(typeof c!=="object"||typeof c.length!=="number"))throw new Error("JSON.stringify");return l("",
{"":a})};if(typeof JSON.parse!=="function")JSON.parse=function(a,c){function d(f,i){var e,b,h=f[i];if(h&&typeof h==="object")for(e in h)if(Object.hasOwnProperty.call(h,e)){b=d(h,e);if(b!==undefined)h[e]=b;else delete h[e]}return c.call(f,i,h)}p.lastIndex=0;if(p.test(a))a=a.replace(p,function(f){return"\\u"+("0000"+f.charCodeAt(0).toString(16)).slice(-4)});if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){a=eval("("+a+")");return typeof c==="function"?d({"":a},""):a}throw new SyntaxError("JSON.parse");}})();
 
//fuck IE
var console;
if(!console){
   console={
	   info:function(){},
	   log:function(){}
   };
}	

(function ($) {
	/*
	 * 创建下拉列表
	 */
	$.fn.combox = function (options) {
		var $this = this;

		// 初始化codelist
		var initCodelist = function (callback) {
			/* codelist */
			var codelist = $this.attr('data-codelist');
			if (!codelist) {
				setSelected();
				return;
			}
			$.get(keter.context + '/public/codelist/' + codelist, function (data) {
				if (!data) return;
				var str = [];
				for (var p in data) {
					var obj = data[p];
					str.push('<option value="' + p + '">' + obj + '</option>');
				}
				$this.html(str.join(''));
				setSelected();
				if (callback) callback();
			});
		};

		// 设置选定功能
		var setSelected = function () {
			var selectedValue = $this.attr('data-value');
			if (!selectedValue) return;
			$this.val(selectedValue);
		};

		var main = function () {
			initCodelist();
		}; main();
	};

	/*
	 * 创建表格
	 */
	$.fn.createTable = function (options) {
		var $data = options.data,
			rowFn = options.rowFn || $.noop,
			updateFn = options.updateFn || $.noop,
			deleteFn = options.deleteFn || $.noop,
			codelists = {}; // 用户存放codelist
		var oTable = null; // table控件

		var tableDiv = $('.kt_table'),
			// 默认的数据操作方式
			dataDefaultOperator = tableDiv.attr('data-default-operator'),
			// 保存用户列
			customColumn = null,
			cell = $('.kt_table .cell'),
			hiddenData = {}; // 保存隐藏数据

		if (dataDefaultOperator === 'true') {
			customColumn = eval(tableDiv.attr('data-custom-column'));
		}

		var getCustomItem = function () {
			var str = [];
			for (var i = 0, len = cell.length; i < len; i++) {
				var temp = cell.eq(i),
					itemValue = temp.attr('data-value');
				str.push(itemValue);
			}
			return str;
		};
			
		var create = function () {
			var len = $data.length,
				$dataFn = {},
				str = [];
			var itemValues = getCustomItem();
			
			str.push('<table class="table table-striped table-hover table-condensed table-bordered" id="oscar_table">');
			str.push('<thead class="thead">');
			str.push('<tr>');
			for(var j = 0; j < itemValues.length; j++) {
				var width = cell.eq(j).attr('width'), // 获得宽度
					dataFn = cell.eq(j).attr('data-fn'), // 设置表格方法
					dataColumnHidden = cell.eq(j).attr('data-column-hidden'), // 隐藏列
					dataLabel = cell.eq(j).attr('data-label'); // 获得列表显示内容
				var codelist = cell.eq(j).attr('data-coldelist');
				// 存放codelist
				if (codelist) {
					codelists[j] = codelist;
					str.push('<th width="' + width + '" class="' + codelist + '">' + dataLabel + '</th>');
				} else if (dataFn) { // 存储用户函数
					str.push('<th width="' + width + '">' + dataLabel + '</th>');
					$dataFn[cell.eq(j).attr('data-value')] = (eval(dataFn));
				} else if (dataColumnHidden && dataColumnHidden === 'true') { // 隐藏数据
					str.push('<th width="' + width + '" class="table_hidden">' + dataLabel + '</th>');
					hiddenData[j] = true;
				} else {
					str.push('<th width="' + width + '">' + dataLabel + '</th>');
				}
			}
			if (dataDefaultOperator === 'true') str.push('<th width="10%">操作</th>');
			str.push('</tr>');
			str.push('</thead><tbody>');
			for (var i = 0; i < len; i++) { // 循环行
				var obj = $data[i],
					str2 = [];
				str.push('<tr>');
				for (var loop = 0; loop < itemValues.length; loop++) { // 循环列
					// 设置codelist
					var clist = codelists[loop] ? 'data-codelist=' + codelists[loop] : '';
					// 设置隐藏
					var hideClass = hiddenData[loop] ? 'table_hidden' : '';
					var tdValue = obj[itemValues[loop]] || '-';
					str2.push('<td class="' + hideClass + '"' + clist + ' id="' + itemValues[loop] + i + '" name="' + itemValues[loop] + '">' + tdValue + '</td>');
					$.data(tableDiv, ( itemValues[loop] + i ), obj[itemValues[loop]] );
				}
				str.push(str2.join(''));
				if (dataDefaultOperator === 'true') { // 添加操作区域
					str.push('<td class="operator" name="customColumn"><a data-index="' + i + '" class="update" href="#">修改</a>&nbsp;&nbsp;<a class="delete" href="#" data-index="' + i + '">删除</a></td>');
				}
				str.push('</tr>');
			}
			str.push('</tbody></table>');
			tableDiv.html(str.join(''));

			var $tableElement = $('.table');

			// 设置自定义函数
			for (var pp in $dataFn) {
				var $td = $tableElement.find('td[name="' + pp + '"]'),
					$fn = $dataFn[pp];
				$td.each(function (index, node) {
					var $node = $(node),
						$id = $node.attr('id'),
						data = $.data(tableDiv, $id),
						result = $fn( $node.html(), $node.parent(), data);
					$node.html(result);
				});
			}

			// 设置自定义列
			if (customColumn) {
				var $td = $tableElement.find('td[name="customColumn"]');
				$td.each(function (index, node) {
					var $node = $(node),
						result = customColumn($node.parent());
					$node.html(result);
				});
			}
			
			oTable = $tableElement.dataTable(
				{
					"bFilter": false
					,"bAutoWidth": false
					,"aaSorting" : [ ] // 默认不排序
					,'oLanguage': {
						"sZeroRecords": '当前没有记录显示'
						,"sInfo": "从 _START_ 到 _END_ 条记录 共有 _TOTAL_ 条记录"
						,"sInfoEmpty": "显示 0 从 0 到 0 条记录"
						,"sInfoFiltered": "(filtered from _MAX_ total records)"
						/*
						,"sLengthMenu": '每页显示<select>'+
								'<option value="10">5</option>'+
								'<option value="20">10</option>'+
								'<option value="30">20</option>'+
								'<option value="-1">全部</option>'+
								'</select> 条记录'
						*/
						,"sLengthMenu" : '显示 _MENU_ 条'
						,"oPaginate": {
							"sFirst": "第一页"
							,'sLast' : '最后一页'
							,'sNext' : '下一页'
							,'sPrevious' : '前一页'
						}
					}
					,'sDom' : 'rt<"bottom fix"<"item2 fix"p><"item2 fix"i><"item2 fix"l>>'
				}
			);

			oTable._gridData = $data;

			// 获得数据
			oTable.getGridData = function () {
				return oTable._gridData;
			};
			
			// 根据索引获得行数据
			oTable.getRowDataByIndex = function (/* Number */ index) {
				if (oTable._gridData && oTable._gridData.length > 0) {
					return oTable._gridData[index];
				}
				return null;
			};

			regEvent(oTable);
		};

		// 注册事件
		var regEvent = function (oTable) {
			// 注册行事件
			oTable.$('tr').click(function (e) {
				// 传递选中行的值
				var data = oTable.fnGetData(this);
				rowFn(data);
				stopBubble(e);
			});

			// 注册默认的按钮
			if (dataDefaultOperator === 'true' && !customColumn) {
				// 更新按钮
				tableDiv.find('.update').click(function (e) {
					var data = oTable._(this.parentNode.parentNode);
					stopBubble(e);
					updateFn(data[0]);
				});
				// 删除按钮
				tableDiv.find('.delete').click(function (e) {
					var data = oTable._(this.parentNode.parentNode);
					stopBubble(e);
					deleteFn(data[0]);
				});
			}
		};

		// 获得代码表
		var getCodeList = function () {
			for (var p in codelists) {
				var temp = codelists[p];
				$.get( keter.context + '/public/codelist/' + temp, function( data ) {
					window[temp] = data;
					var $th = tableDiv.find('td[data-codelist=' + temp + ']'), // 获得相关的th
						$value = $th.html();
					$th.html(data[$value]);
				});
			}
		};
		
		var main = function () {
			create();
			getCodeList();
		}; main();
		return oTable;
	};

	window.stopBubble = function (e) {
		//如果提供了事件对象，则这是一个非IE浏览器
		if(e && e.stopPropagation) {
			//因此它支持W3C的stopPropagation()方法
			e.stopPropagation();
		} else {
			//否则，我们需要使用IE的方式来取消事件冒泡 
			window.event.cancelBubble = true;
		}
		return false;
	};
	
	window.getTargetElement = function (event) {
		return event.srcElement ? event.srcElement : event.target;
	};

	// 停止默认事件
	window.stopDefault = function (e) {
		//如果提供了事件对象，则这是一个非IE浏览器 
		if(e && e.preventDefault) {
			//阻止默认浏览器动作(W3C)
			e.preventDefault();
		} else {
			//IE中阻止函数器默认动作的方式 
			window.event.returnValue = false; 
		}
		return false;
	};

	window.getPostData = function (str) {  
		var value = {};
		var queryString = str,  
			paraNames = queryString.split('&');  
		for (var i = 0; i < paraNames.length; i++) {  
			var start = paraNames[i].split('=');  
			if (start.length > 0) {
				value[start[0]] = start[1];
			}
		}
		return value;
	};

	window.getParameter = function (name) {
		var url = document.location.href,
			start = url.indexOf("?")+1;
		if (start == 0) return "";
		
		var value = "",
			queryString = url.substring(start),
			paraNames = queryString.split("&");

		for (var i = 0; i < paraNames.length; i++) {
			if (name == getParameterName(paraNames[i])) {
				value = getParameterValue(paraNames[i]);
			}
		}

		function getParameterName(str) {
			var start = str.indexOf("=");
			if (start == -1) {
				return str;
			}
			return str.substring(0,start);
		}

		function getParameterValue(str) {
			var start = str.indexOf("=");
			if (start == -1) {
				return "";
			}
			return str.substring(start+1);
		}
		return value;
	};

	$.postJSON = function(url, data, callback) {
		//alert(url);
		return jQuery.ajax({
			'type': 'POST',
			'url': url,
			'contentType': 'application/json',
			'data': JSON.stringify(data),
			'dataType': 'json',
			'success': callback,
			'error' : callback
		});
	};

	// ajax from 提交
	$.fn.postFormData = function (options) {
		var $data = options || {},
			$form = $(this),
			url = $form.attr('action');
			
		var defaultSubmit = function (callback) {
			$form.submit(function (e) {
				stopDefault(e);
				var postData = getPostData($form.serialize());
				$.postJSON(url, postData, function(data){
					if (callback) callback(data);
				});
			});
		};
		
		var customSubmit = function (callback) {
			$form.submit(function (e) {
				stopDefault(e);
				var postData = getPostData($form.serialize());
				if (callback) callback(postData);
			});
		};

		return {
			defaultSubmit : defaultSubmit
			, customSubmit : customSubmit
		}
	};
	
	/**
	 * 系统默认操作成功函数
	 */
	window.success = function(data,reload){
		if(data.message === 'SUCCESS'){
			alert('操作成功！');
		}
		if(reload){
			window.location.reload();
		}
	}
	
	/**
	 * 根据状态信息返回结果显示内容
	 */
	window.getStatusName = function(status){
		var result = ""
		if(status=='EDIT'){
			result = "编辑";
		}
		if(status=='SUBMIT'){
			result = "提交 | 待审核";
		}
		if(status=='REJECT'){
			result = "未通过";
		}
		if(status=='PASS'){
			result = "通过";
		}
		return result;
	}
	
	/*
	 * 初始化kindEditor
	 */
	window.initKindEditor = function (callback) {
		var editor;
		KindEditor.ready(function (K) {
			editor = K.create('textarea[name="content"]', {
				resizeType : 1,
				allowPreviewEmoticons : false,
				allowImageUpload : false,
				items : [
					'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
					'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
					'insertunorderedlist', '|']//, 'emoticons'
			});
			if (callback) {
				callback(editor);
			}
		});
	};

	/*
	 * alert控件
	 */
	// 弹出框
	var $popBox;
	setTimeout(function () {
		$popBox =  $(this).popBox({top : '200px'});
	}, 300);

	$.keterAlert = function (data, callback) {
		var init = function () {
			var str = [];
			str.push('<div class="glyphicon glyphicon-warning-sign" style="padding:40px 0; font-size:18px;"> ' + data.message +  '</div>');
			str.push('<div style="height:58px; line-height:58px; background:#F1F1F1;"><button class="btn btn-success" id="keterAlertOK">&nbsp;确定&nbsp;</button></div>');
			$popBox.setContent(str.join(''));
			$popBox.show();
			$('#keterAlertOK').click(function () {
				$popBox.hide();
				if (callback) callback();
			});
		};
		
		var main = function () {
			init();
		}; main();
	};
})(jQuery);

// 智能浮动功能
(function ($) {
	$.fn.smartFloat = function (options) {
		var $this = this
			, params = $.extend({}, options)
			, $parentContainer = params.parentContainer //父容器
			, $window = $(window);
		var top = 0; // 获得对象相对于窗口的高度
		if ($parentContainer) {
			top = $parentContainer.position().top;
		} else {
			top = $this.position().top;
		}
		// 获得窗口滚动的高度
		$window.scroll(function (e) {
			var $windowTop = $(this).scrollTop();
			if ($windowTop >= top) {
				$this.css({'position' : 'fixed', 'top' : '5px'});
			} else {
				$this.css({'position' : 'static'});
			}
		});
	};
}) (jQuery);
